package com.xinqi.modules.sys.textbook.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.enums.YesNoEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.textbook.convert.CloudTextbookContentConvert;
import com.xinqi.modules.sys.textbook.domain.CloudTextbookContentEntity;
import com.xinqi.modules.sys.textbook.dto.req.CloudTextbookContentCreateDTO;
import com.xinqi.modules.sys.textbook.dto.req.CloudTextbookContentDeleteDTO;
import com.xinqi.modules.sys.textbook.dto.req.CloudTextbookContentQueryDTO;
import com.xinqi.modules.sys.textbook.dto.req.CloudTextbookContentReplaceDTO;
import com.xinqi.modules.sys.textbook.dto.req.CloudTextbookContentUpdateDTO;
import com.xinqi.modules.sys.textbook.dto.rsp.CloudTextbookContentResultDTO;
import com.xinqi.modules.sys.textbook.manager.CloudTextbookCatalogManager;
import com.xinqi.modules.sys.textbook.manager.CloudTextbookContentManager;
import com.xinqi.modules.sys.textbook.service.CloudTextbookContentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 云课本课堂内容服务层实现
 *
 * @author: linkai
 * @date: 2023/04/25
 */
@Validated
@Service("cloudTextbookContentService")
@RequiredArgsConstructor
public class CloudTextbookContentServiceImpl implements CloudTextbookContentService {
    private final CloudTextbookContentConvert cloudTextbookContentConvert;
    private final CloudTextbookContentManager cloudTextbookContentManager;
    private final CloudTextbookCatalogManager cloudTextbookCatalogManager;

    /**
     * 分页查询 云课本课堂内容数据
     */
    @Override
    @DS("slaver")
    public PageInfo<CloudTextbookContentResultDTO> page(Param pageable, CloudTextbookContentQueryDTO query) {
        IPage<CloudTextbookContentEntity> page = cloudTextbookContentManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, cloudTextbookContentConvert::convert);
    }

    /**
     * 查询 云课本课堂内容数据
     */
    @DS("slaver")
    @Override
    public List<CloudTextbookContentResultDTO> find(CloudTextbookContentQueryDTO query) {
        return cloudTextbookContentManager.list(wrapper(query)).stream()
            .map(cloudTextbookContentConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<CloudTextbookContentEntity> wrapper(CloudTextbookContentQueryDTO query) {
        LambdaQueryWrapper<CloudTextbookContentEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(CloudTextbookContentEntity::getId, v));
        Queries.accept(query.getBookId(), v -> wrapper.eq(CloudTextbookContentEntity::getCloudTextbookId, v));
        Queries.accept(query.getCatalogId(), v -> wrapper.eq(CloudTextbookContentEntity::getRefId, v));
        wrapper.orderBy(true, true, CloudTextbookContentEntity::getPageNum);
        return wrapper;
    }

    /**
     * 根据id查询 云课本课堂内容数据
     */
    @DS("slaver")
    @Override
    public CloudTextbookContentResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(cloudTextbookContentManager.findById(id)).map(cloudTextbookContentConvert::convert).orElse(null);
    }

    /**
     * 新增 云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid CloudTextbookContentCreateDTO dto) {
        CloudTextbookContentEntity entity = cloudTextbookContentConvert.create(dto);
        if (entity.getIsRef() == null) {
            entity.setIsRef(YesNoEnum.NO.ordinal());
        }
        if (Objects.equals(YesNoEnum.YES.ordinal(), entity.getIsRef())) {
            CommonErrors.BAD_REQUEST.check(entity.getRefId() != null, "所属章节ID不能为空");
        }
        cloudTextbookContentManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid CloudTextbookContentUpdateDTO dto) {
        Optional.ofNullable(cloudTextbookContentManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        CloudTextbookContentEntity entity = cloudTextbookContentConvert.update(dto);
        return cloudTextbookContentManager.updateById(entity);
    }

    /**
     * 根据id删除 云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return cloudTextbookContentManager.removeById(id);
    }

    /**
     * 根据id删除 云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(CloudTextbookContentDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertBatch(List<CloudTextbookContentCreateDTO> list) {
        list.forEach(this::insert);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean replace(Long textbookId, List<CloudTextbookContentReplaceDTO> list) {
        list.forEach(v -> replace(textbookId, v));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean replace(Long textbookId, @Valid CloudTextbookContentReplaceDTO dto) {
        CloudTextbookContentEntity entity = Optional.ofNullable(cloudTextbookContentManager.findById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("内容不存在"));
        CommonErrors.BAD_REQUEST.check(Objects.equals(entity.getCloudTextbookId(), textbookId), "内容不属于该课本");
        entity.setIsRef(YesNoEnum.YES.ordinal());
        CommonErrors.BAD_REQUEST.check(cloudTextbookCatalogManager.isExist(textbookId, dto.getRefId()), "目录不存在");
        entity.setRefId(dto.getRefId());
        return this.cloudTextbookContentManager.updateById(entity);
    }

    @DS("slaver")
    @Override
    public List<CloudTextbookContentResultDTO> findByCloudTextbookId(Long textBookId) {
        CloudTextbookContentQueryDTO query = new CloudTextbookContentQueryDTO();
        query.setBookId(textBookId);
        return cloudTextbookContentManager.list(wrapper(query)).stream().map(cloudTextbookContentConvert::convert).collect(Collectors.toList());
    }

}
